<?php
/**
 * 功能: 注册
 * User: 文丹
 * Date: 2018/6/4 0004
 * Time: 9:32
 */

namespace app\index\controller;
use app\validate\User;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Session;

class Register extends Controller{
    /**
     * 发送短信
     */
    public function send(){

        $phone   = trim(input('phone'));
        if(empty($phone)){
            return json(['msg'=>'电话号码不能为空','ok'=>false]);
        }
        $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL
        $randNum = rand(1111,9999);

        $smsConf = array(
            'key'   => config('SMS_appKey'), //您申请的APPKEY
            'mobile'    => $phone, //接受短信的用户手机号码
            'tpl_id'    => '92354', //您申请的短信模板ID，根据实际情况修改
            'tpl_value' =>'#code#='.$randNum.'&#company#=买就省' //您设置的模板变量，根据实际情况修改
        );

        $content = $this->juhecurl($sendUrl,$smsConf,1); //请求发送短信

        if($content){
            $result = json_decode($content,true);
            $error_code = $result['error_code'];
            if($error_code == 0){
                //状态为0，说明短信发送成功
              //  echo "短信发送成功,短信ID：".$result['result']['sid'];
                Session::set('phone',$phone);
                Session::set('code',$randNum);
                Session::set('time',time());

                return json(['msg'=>'短信发送成功','ok'=>true]);
            }else{
                //状态非0，说明失败
                $msg = $result['reason'];
               // echo "短信发送失败(".$error_code.")：".$msg;
                return json(['msg'=>"短信发送失败(".$error_code.")：".$msg,'ok'=>false]);
            }
        }else{
            //返回内容异常，以下可根据业务逻辑自行修改
           // echo "请求发送短信失败";
            return json(['msg'=>"请求发送短信失败，请稍后重试~",'ok'=>false]);
        }
    }

    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    public function juhecurl($url,$params=false,$ispost=0){
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($params){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }


    /**
     * 注册
     */
    public function register(){

        $mark = strtoupper(trim(input('mark')));//邀请码

        if(empty($mark)){
            return json(['msg'=>'邀请码不能为空','ok'=>false]);
        }
        $code =  useful_time(35);
      // $code =  1234;
        $phone = session('phone');
       //$phone = '13183832668';
        if(empty($phone)){
            return json(['msg'=>'没有获取到手机号','ok'=>false]);
        }
        if($code){
            $verify = trim(input('verify'));
            $password = trim(input('password'));
            if(empty($verify)||empty($phone)||empty($password)){
                return json(['msg'=>'请填写完整的数据','ok'=>false]);
            }
            if($verify!=$code){
                return json(['msg'=>'验证码错误','ok'=>false]);
            }else{
                $check = model('User')->find($phone);
                if($check){
                    return json(['msg'=>'你已经注册过了','ok'=>false]);
                }

                $parent = Db::name('user')->where('mark',$mark)->find();
                if($parent){
                    $parent_id = $parent['id'];
                }else{
                    $res = Db::name('plat')->where('mark',$mark)->find();
                    if($res){
                        $parent_id = 0;
                    }else{
                        return json(['msg'=>'邀请码错误','ok'=>false]);
                    }
                }


                // 启动事务
                Db::startTrans();
                try{
                //默认头像
                $photo = Db::name('default')->where('type',1)->find();
                $photo = isset($photo['url'])?$photo['url']:'';
                $data = [
                    'phone'=>$phone,
                    'password'=>md5($password),
                    'parent_id'=>$parent_id,
                    'add_time'=>time(),
                    'photo'=>$photo
                ];
                $user_id = model('User')->add($data);
                $first = randLetter();
                $nickname = $first.$user_id.'用户';//默认昵称
                Db::name('user')->where('id',$user_id)->update(['nickname'=>$nickname]);
                Db::name('user')->where('mark',$mark)->setInc('member');
                $superior =  Db::name('user')->where('mark',$mark)->value('parent_id');//上一级
                if($superior){
                    Db::name('user')->where('id',$superior)->setInc('member');
                }

                    // 提交事务
                    Db::commit();
                    Session::delete('phone');
                    Session::delete('code');
                    return json(['msg'=>'注册成功','ok'=>true]);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return json(['msg'=>'注册失败，请重新注册','ok'=>false]);
                }


            }


        }else{
            return json(['msg'=>'验证码失效','ok'=>false]);
        }

    }

    /**
     * 忘记密码
     */
    public function reset_password(){

        $code = useful_time(35);//验证码有效时间35分钟
       /* dump($code);
       die;*/
        if($code){
            $verify = trim(input('verify',7225));
            $password = trim(input('password',111111));//新密码
            $phone = session('phone');

            if(empty($verify)||empty($phone)||empty($password)){
                return json(['msg'=>'请填写完整的数据','ok'=>false]);
            }
            if($verify!=$code){
                return json(['msg'=>'验证码错误','ok'=>false]);
            }else{
                $data = [
                    'password'=>md5($password),
                    'update_time'=>time(),
                ];
                $result = model('User')->save_user($phone,$data);
                Session::delete('phone');
                Session::delete('code');
                if($result){
                    return json(['msg'=>'重置成功','ok'=>true]);
                }else{
                    return json(['msg'=>'重置失败，请稍后再试','ok'=>false]);
                }

            }

        }else{
            return json(['msg'=>'验证码失效','ok'=>false]);
        }

    }
    /**
     * 取消绑定手机号
     */
    public function cancel(){
        $code =  useful_time(35);
        if($code){
            $verify = trim(input('verify'));
            $token  = trim(input('token'));
            $check  = model('User')->checkToken($token);
            if(empty($check)){
                return json(['msg'=>'你还未登录，或者登录被占用','ok'=>false]);
            }
            if($code!=$verify){
                return json(['msg'=>'验证码错误','ok'=>false]);
            }
            $phone   = session('phone');
            $user_id = Db::name('user')->where('token',$token)->where('phone',$phone)->value('id');

            if($user_id){
               // session('user_id',$user_id);
                return json(['msg'=>'请求成功','ok'=>true]);
            }else{
                return json(['msg'=>'该手机号不存在','ok'=>false]);
            }

        }else{
            return json(['msg'=>'验证码失效','ok'=>false]);
        }

    }


    /**
     * 更换手机号
     */
    public function replace(){
        $code =  useful_time(35);
        if($code){
            $verify = trim(input('verify'));
            $new_phone = session('phone');
           // $user_id   = session('user_id');
            $token   = trim(input('token'));
            $user_id   = model('User')->gerUserId($token);
            if(empty($user_id)){
                return json(['msg'=>'参数错误','ok'=>false]);
            }
            if(empty($verify)||empty($new_phone)){
                return json(['msg'=>'请填写完整的数据','ok'=>false]);
            }
            $check = Db::name('user')->whereNotIn('id',$user_id)->where('phone',$new_phone)->find();
            if($check){
                return json(['msg'=>'该手机号已经被绑定了','ok'=>false]);
            }
            if($verify!=$code){
                return json(['msg'=>'验证码错误','ok'=>false]);
            }else{
                $data = [
                    'phone'=>$new_phone,
                    'update_time'=>time(),
                ];
                $result = Db::name('user')->where('id',$user_id)->update($data);
                Session::delete('phone');
                Session::delete('code');
                Session::delete('user_id');
                if($result){
                    return json(['msg'=>'更换成功','ok'=>true]);
                }else{
                    return json(['msg'=>'更换失败，请稍后再试','ok'=>false]);
                }

            }

        }else{
            return json(['msg'=>'验证码失效','ok'=>false]);
        }

    }


}